import { _decorator, Label, RichText, tween, Vec3 } from 'cc';
import { BaseUI } from '../../framework/base/BaseUI';
import { ADType, BaseEventName } from '../../framework/config/Appcfg';
import { AudioMgr } from '../../framework/manager/AudioMgr';
import { SDKMgr } from '../../framework/manager/SDKMgr';
import { UIMgr } from '../../framework/manager/UIMgr';
import { TimeUtils } from '../../framework/utils/TimeUtils';
import { AudioId, UIID } from '../config/Config';
import { GameDef } from '../gameLogic/GameDef';
import { PlayerMgr } from '../manager/PlayerMgr';
import { GuildCfg } from './UIGuide';
const { ccclass, property } = _decorator;

@ccclass('UIOver')
export class UIOver extends BaseUI {
    tipText: any = null
    isWin: boolean = false
    gameType: number = 0;
    public init(param1?: any, param2?: any, param3?: any, param4?: any, param5?: any): void {
        this.tipText = param1
        this.isWin = param2
        this.gameType = param3
    }

    start() {
        //视频复活
        this.findChilds("btnRePlay").on("click", this.onRePlay, this)
        this.findChilds("btnRePlayWin").on("click", this.onRePlay, this)
        //回到首页
        this.findChilds("backHome_lose").on("click", this.onBackHome, this)
        //回到首页
        this.findChilds("backHome").on("click", this.onPlayNextLevel, this)
        //视频双倍积分
        this.findChilds("getdbScore").on("click", this.onVideoGetRware, this)
    }
    protected onEnable(): void {
        this.findChilds("loseText").active = !this.isWin;
        this.findChilds("winText").active = false;
        this.exitstagePro()
        if (this.isWin) {
            AudioMgr.getInstance().playEffect(AudioId.victory);
            let winCount = GameDef.instance.getCurrGameWin(true);
            if (this.gameType != 3) {
                PlayerMgr.instance.userData.gameScore += GameDef.instance.currLevelTotalPoints
            }
            this.setWinTip(winCount);
            UIMgr.instance.showNodeByUIID(UIID.PREFAB_RibbonEffect)
            this.findChilds("scoeNum").getComponent(Label).string = `${GameDef.instance.currLevelTotalPoints}`; //+GameDef.instance.currLevelTotalScore;
            PlayerMgr.instance.userData.uplevel(this.gameType)
        } else {
            AudioMgr.getInstance().playEffect(AudioId.defeat)
            GameDef.instance.getCurrGameWin(false)
        }
        this.findChilds("winNode").active = this.isWin;
        this.findChilds("loseNode").active = !this.isWin;
        this.findChilds("winBtns").active = this.isWin;
        this.findChilds("loseBtns").active = !this.isWin;
        this.findChilds("getdbScore").active = PlayerMgr.getInstance().getGuideData().isGuideEnd();
        this.scheduleOnce(() => {
            this.showGuide()
        }, 0.5);
        this.findChilds("proTextNode").getComponent(Label).string = `${GameDef.instance.reportInfo.levelPorgress}%`;
        tween(this.findChilds("zhhongdian"))
            .by(0.01, { position: new Vec3(38, 20, 0) })
            .to(1.5, { position: new Vec3(38+ 490*(GameDef.instance.reportInfo.levelPorgress/100), 20, 0) })
            .start()
    }
    exitstagePro(){
        SDKMgr.getInstance().reportEvent("exitstage", {
            "level_type": "主线",
            "stage": `第${GameDef.instance.curLevel}关`,
            "passstage": this.isWin ? 1 : 0,
            "exit_info": this.isWin ? "胜利" : "失败",
            "revivetime": GameDef.instance.reportInfo.revivetime,
            "tip": GameDef.instance.reportInfo.tip,
            "refresh": GameDef.instance.reportInfo.refresh,
            "knock": GameDef.instance.reportInfo.knock,
            "passpercent": GameDef.instance.reportInfo.levelPorgress,
            "points": GameDef.instance.currLevelTotalPoints,
            "ad_video_times": GameDef.instance.reportInfo.ad_video_times,
            "max_combo": GameDef.instance.comboCount,
        })
        
    }
    setWinTip(winCount: number) {
        return;
        let count = 0
        let combo = PlayerMgr.instance.userData.setHisMaxCombo(GameDef.instance.comboCount)
        let score = PlayerMgr.instance.userData.setHisMaxScore(GameDef.instance.currLevelTotalPoints)
        let win = PlayerMgr.instance.userData.setHisMaxWin(winCount)
        combo && count++;
        score && count++;
        win && count++;
        let str = "";


        // str +=`<color=#ff534e>${GameDef.instance.currLevelTotalPoints}<color=#c6945f>分</color></color>\n`;//${score?"历史最佳":""}//分数
        str += `<color=#ff534e>${GameDef.instance.comboCount}<color=#c6945f>次</color></color>\n`; //${combo?"历史最佳":""}
        str += `<color=#ff534e>${winCount}<color=#c6945f>场</color></color>\n`;//${win?"历史最佳":""}
        str += `<color=#ff534e>${TimeUtils.SecondToHours(GameDef.instance.currGameTime, true)}</color>\n`;
        str += `<color=#ff534e>${PlayerMgr.instance.userData.gameScore}<color=#c6945f>分</color></color>\n`;
        this.findChilds("rigthText").getComponent(RichText).string = str;
        this.findChilds("topText").getComponent(RichText).string = ""; //`<color=#82848e>恭喜你，本次获得<color=#fc8027>${count}</color>次历史最佳!</color>`;
        this.findChilds("zan0").active = combo
        this.findChilds("zan1").active = win
        this.findChilds("zan2").active = false
    }

    onCloseBtn() {
        this.onToCloseView()
    }
    onRePlay() {
        SDKMgr.getInstance().reportEvent("enterstage", {
            "level_type": "主线",
            "stage": `第${GameDef.instance.curLevel}关`
        })

        if (PlayerMgr.instance.userData.data.roleHp <= 0 && !PlayerMgr.instance.isUnlimitedHp()) {
            UIMgr.instance.openUI(UIID.UIPower, UIID.Default, 1, "体力恢复", () => {
                PlayerMgr.instance.userData.addRoleHp(-1)
                this.onToCloseView()
                this.sendEvent(BaseEventName.ReplayGame)
                console.log("恢复体力之后直接游戏");

            })
            return;
        }

        this.onToCloseView()
        this.sendEvent(BaseEventName.ReplayGame)
    }
    onVideoGetRware() {
        SDKMgr.getInstance().playVideo((isComp) => {
            if (isComp) {
                this.onToCloseView();
                UIMgr.getInstance().closeById(UIID.UIGame);
                UIMgr.getInstance().openUI(UIID.UIHome, UIID.Default);
                if (this.isWin && this.gameType != 3) {
                    PlayerMgr.instance.userData.gameScore += GameDef.instance.currLevelTotalPoints;
                }
                console.log("视频双倍积分");
            };
            SDKMgr.getInstance().reportEvent("showad", {
                "adtype": "video",
                "opportunity": ADType.DoublePOINT,
                "passpercent": GameDef.instance.reportInfo.levelPorgress,
                "video_complete": isComp + '',
                "is_stage": "true",
                "stage": `第${GameDef.instance.curLevel}关`,
                "level_type": "主线",
            })
        }, ADType.DoublePOINT)

    }
    onBackHome() {
        this.onToCloseView()
        UIMgr.getInstance().closeById(UIID.UIGame)
        UIMgr.getInstance().openUI(UIID.UIHome, UIID.Default)
    }
    onPlayNextLevel(){
        this.onToCloseView()
        SDKMgr.getInstance().reportEvent("enterstage", {
            "level_type": "主线",
            "stage": `第${GameDef.instance.curLevel}关`
        })
        this.sendEvent(BaseEventName.playNextLevel,this.gameType)
        console.log("下一关")
    }
    onToCloseView() {
        this.closeUI()
        UIMgr.instance.hideNodeByUIID(UIID.PREFAB_RibbonEffect)
    }
    update(deltaTime: number) {

    }

    showGuide() {
        // if(!PlayerMgr.instance.isNewGuide) return
        let guideData = PlayerMgr.getInstance().getGuideData();
        if (!guideData.isGuideEnd()) {
            let guideCfg = new GuildCfg();
            guideCfg.closeUICallBack = () => {
                setTimeout(() => {
                    if (this.getGuideData(guideData.currentId)) {
                        this.showGuide()
                    }
                }, 500)
            }
            const data = this.getGuideData();
            guideCfg.distNode = data.distNode;
            guideCfg.isWeek = data.isWeek;
            guideCfg.tipstring = data.tipstring;
            guideCfg.handOffset = data.handOffset;
            this.openUICallBack(UIID.UIGuide, () => {
                guideData.addCurrentId(data.isEnd)
            }, guideCfg);

        }
    }

    getGuideData(id: number = null) {
        let guideData = PlayerMgr.getInstance().getGuideData();
        switch (id || guideData.currentId) {
            case 6:
                //引导
                return { distNode: this.findChilds("backHome"), tipstring: "你已经掌握了十字消除的基本玩法啦，\n快去下一关开启你的消除之旅吧~", isWeek: false, isEnd: true, handOffset: new Vec3(72, -90, 0) }

        }
    }
}
